<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联竞赛" prop="competitionId">
        <el-select v-model="queryParams.competitionId" placeholder="请选择竞赛" clearable>
          <el-option
            v-for="item in competitionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="奖项层次" prop="awardLevel">
        <el-select v-model="queryParams.awardLevel" placeholder="请选择奖项层次" clearable>
          <el-option
            v-for="item in awardLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="奖项等级" prop="awardGrade">
        <el-select v-model="queryParams.awardGrade" placeholder="请选择奖项等级" clearable>
          <el-option
            v-for="item in awardGradeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分值" prop="scoreValue">
        <el-input
          v-model="queryParams.scoreValue"
          placeholder="请输入分值"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否禁用(0否1是)" prop="isDisabled">
        <el-input
          v-model="queryParams.isDisabled"
          placeholder="请输入是否禁用(0否1是)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除(0否2是)" prop="isDeleted">
        <el-input
          v-model="queryParams.isDeleted"
          placeholder="请输入是否删除(0否2是)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:config:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scoreList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="唯一标识ID" align="center" prop="id" />
      <el-table-column label="关联竞赛" align="center" prop="competitionId" :formatter="formatCompetitionName" />
      <el-table-column label="奖项层次" align="center" prop="awardLevel" :formatter="formatAwardLevel" />
      <el-table-column label="奖项等级" align="center" prop="awardGrade" :formatter="formatAwardGrade" />
      <el-table-column label="分值" align="center" prop="scoreValue" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['competitionmanagement:score:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['competitionmanagement:score:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改竞赛分值对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="scoreRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联竞赛" prop="competitionId">
          <el-select v-model="form.competitionId" placeholder="请选择竞赛" @change="onCompetitionChange">
            <el-option
              v-for="item in competitionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-divider content-position="left">奖项分值设置</el-divider>
        
        <div v-for="(item, index) in form.scoreItems" :key="index">
          <el-row :gutter="10">
            <el-col :span="7">
              <el-form-item :label="index === 0 ? '奖项层次' : ''" :prop="'scoreItems.' + index + '.awardLevel'" :rules="{required: true, message: '奖项层次不能为空', trigger: 'change'}">
                <el-select v-model="item.awardLevel" placeholder="请选择奖项层次">
                  <el-option
                    v-for="level in awardLevelOptions"
                    :key="level.value"
                    :label="level.label"
                    :value="level.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item :label="index === 0 ? '奖项等级' : ''" :prop="'scoreItems.' + index + '.awardGrade'" :rules="{required: true, message: '奖项等级不能为空', trigger: 'change'}">
                <el-select v-model="item.awardGrade" placeholder="请选择奖项等级">
                  <el-option
                    v-for="grade in awardGradeOptions"
                    :key="grade.value"
                    :label="grade.label"
                    :value="grade.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item :label="index === 0 ? '分值' : ''" :prop="'scoreItems.' + index + '.scoreValue'" :rules="{required: true, message: '分值不能为空', trigger: 'blur'}">
                <el-input v-model="item.scoreValue" placeholder="请输入分值" />
              </el-form-item>
            </el-col>
            <el-col :span="3" v-if="form.scoreItems.length > 1">
              <el-button type="danger" icon="Delete" circle @click="removeScoreItem(index)" />
            </el-col>
          </el-row>
        </div>
        
        <el-form-item>
          <el-button type="primary" icon="Plus" @click="addScoreItem">添加奖项分值</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Score">
import { listScore, getScore, delScore, addScore, updateScore } from "@/api/competitionmanagement/score";
import { getCompetition, listCompetition } from "@/api/competitionmanagement/competition";

const { proxy } = getCurrentInstance();

const scoreList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 竞赛选项列表
const competitionOptions = ref([]);

const data = reactive({
  form: {
    competitionId: null,
    scoreItems: [
      {
        awardLevel: null,
        awardGrade: null,
        scoreValue: null
      }
    ]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    competitionId: null,
    awardLevel: null,
    awardGrade: null,
    scoreValue: null,
    isDisabled: null,
    isDeleted: null
  },
  rules: {
    competitionId: [
      { required: true, message: "关联竞赛不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 奖项层次选项
const awardLevelOptions = ref([
  { value: '0', label: '校级' },
  { value: '1', label: '市级' },
  { value: '2', label: '省部级' },
  { value: '3', label: '国家级' }
]);

// 奖项等级选项
const awardGradeOptions = ref([
  { value: '0', label: '一等奖' },
  { value: '1', label: '二等奖' },
  { value: '2', label: '三等奖' },
  { value: '3', label: '优秀奖' },
  { value: '4', label: '参与奖' }
]);

/** 查询竞赛分值列表 */
function getList() {
  loading.value = true;
  listScore(queryParams.value).then(response => {
    scoreList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询竞赛列表 */
function getCompetitionList() {
  listCompetition({}).then(response => {
    competitionOptions.value = response.rows.map(item => {
      return {
        value: item.id,
        label: item.competitionName
      };
    });
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 添加奖项分值行 */
function addScoreItem() {
  form.value.scoreItems.push({
    awardLevel: null,
    awardGrade: null,
    scoreValue: null
  });
}

/** 删除奖项分值行 */
function removeScoreItem(index) {
  form.value.scoreItems.splice(index, 1);
}

/** 竞赛选择变化事件 */
function onCompetitionChange() {
  // 可以在这里添加竞赛变化时的逻辑，比如根据竞赛加载已有的奖项分值设置
}

// 表单重置
function reset() {
  form.value = {
    competitionId: null,
    scoreItems: [
      {
        awardLevel: null,
        awardGrade: null,
        scoreValue: null
      }
    ]
  };
  proxy.resetForm("scoreRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加竞赛分值";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getScore(_id).then(response => {
    // 将单条数据转换为表单需要的格式
    form.value = {
      id: response.data.id,
      competitionId: response.data.competitionId,
      scoreItems: [
        {
          awardLevel: response.data.awardLevel,
          awardGrade: response.data.awardGrade,
          scoreValue: response.data.scoreValue
        }
      ]
    };
    open.value = true;
    title.value = "修改竞赛分值";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scoreRef"].validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      // 验证每个奖项分值行
      let isValid = true;
      let errorMessage = "";
      
      form.value.scoreItems.forEach((item, index) => {
        if (!item.awardLevel) {
          isValid = false;
          errorMessage = `第${index + 1}行：奖项层次不能为空`;
        } else if (!item.awardGrade) {
          isValid = false;
          errorMessage = `第${index + 1}行：奖项等级不能为空`;
        } else if (!item.scoreValue) {
          isValid = false;
          errorMessage = `第${index + 1}行：分值不能为空`;
        }
      });
      
      if (!isValid) {
        proxy.$modal.msgError(errorMessage);
        return;
      }
      
      // 为每一条数据分别发送请求
      const promises = [];
      form.value.scoreItems.forEach(item => {
        const submitData = {
          competitionId: form.value.competitionId,
          awardLevel: item.awardLevel,
          awardGrade: item.awardGrade,
          scoreValue: item.scoreValue
        };
        
        // 如果是修改操作，添加ID
        if (form.value.id) {
          submitData.id = form.value.id;
        }
        
        if (form.value.id) {
          promises.push(updateScore(submitData));
        } else {
          promises.push(addScore(submitData));
        }
      });
      
      // 等待所有请求完成
      Promise.all(promises).then(responses => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgError("操作失败：" + error.message);
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除竞赛分值编号为"' + _ids + '"的数据项？').then(function() {
    return delScore(_ids);  
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('learning/score/export', {
    ...queryParams.value
  }, `score_${new Date().getTime()}.xlsx`)
}

// 格式化竞赛名称
function formatCompetitionName(row) {
  const competitionId = row.competitionId;
  if (!competitionId) return "";
  
  // 从竞赛选项列表中查找竞赛名称
  const competition = competitionOptions.value.find(item => item.value === competitionId);
  return competition ? competition.label : "未知竞赛";
}

// 格式化奖项层次
const formatAwardLevel = (row, column) => {
  const level = row.awardLevel;
  const option = awardLevelOptions.value.find(item => item.value === level?.toString());
  return option ? option.label : level;
};

// 格式化奖项等级
const formatAwardGrade = (row, column) => {
  const grade = row.awardGrade;
  const option = awardGradeOptions.value.find(item => item.value === grade?.toString());
  return option ? option.label : grade;
};

getList();
getCompetitionList();
</script>
